<template>
  <div>
    <div class="bg-[rgba(55,33,255,0.03)] rounded-[8px] px-[15px] py-[15px]">
      <Icon :size="14" icon="ep:bell-filled" color="#3721FF"/>
      设置偏远地区后，商品如果有设置偏远地区运费，且用户下单时填写地址符合，运费
      会替换成偏远地区运费

    </div>


    <div class="mt-[32px]">
      <el-form label-width="85px" :rules="rules" :model="form" ref="FormRef">
        <el-form-item :label="item.name" :prop="item.code"
                      v-for="(item,index) in config"
                      :key="index"
        >

          <el-input v-model="form[item.code]"
                    v-if="!item.type"
          />
          <el-select v-model="form[item.code]"
                     v-if="item.type == 'select'"
                     @change="onChange(item.code)"
          >
            <el-option v-for="(it,idx) in item.list" :key="idx"
                       :label="it[item.label]" :value="it[item.value]"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>
<script setup lang="ts">
import Icon from "@/components/Icon/src/Icon.vue";
import {listToMap, formError, deepCopy} from "@/utils";
import {GlobeStateApi} from "@/api/logistics/globestate";
import {GlobeStateRemoteApi} from "@/api/logistics/remoteArea";
import {GlobeStateMethodApi} from "@/api/method";
import {GlobeStateDetailApi} from "@/api/globestatedetail";
import {getGlobeState} from '@/api/publicInterf'

const props = defineProps({
  info: {
    type: Object,
    required: false,
    default: () => {
    }
  }
})

const FormRef = ref(null)
const config = ref([
  {
    name: "地区",
    code: "stateId",
    label: "stateName",
    type: "select",
    value: "id",
    list: []
  },
  {
    name: "一级区域",
    code: "province",

    label: "name",
    type: "select",
    value: "name",
  },
  {
    name: "二级区域",
    code: "city",

    label: "name",
    type: "select",
    value: "name",
  }
])

const rules = computed(() => {
  let map = listToMap(config.value, 'code');
  for (let i in map) {
    if (map[i].type == 'select') {
      map[i] = [{required: true, message: `请选择${map[i].name}`, trigger: 'change'}]
    } else {
      map[i] = [{required: true, message: `请输入${map[i].name}`, trigger: 'blur'}]
    }

  }
  return map
})

const form = ref({})

const provinceData = ref([])


const confirm = async () => {

  try {
    await FormRef.value && FormRef.value.validate();


    let option = {
      ...form.value,
    }

    if (form.value.id) {
      await GlobeStateRemoteApi.updateGlobeStateRemote(option);
    } else {
      await GlobeStateRemoteApi.createGlobeStateRemote(option);
    }
  } catch (e) {
    formError()
  }

}


const onChange = code => {
  if (code == "stateId") {
    form.value.methodId = "";
    form.value.province = "";
    form.value.city = "";

    initPromise();
  } else if (code == "province") {
    form.value.city = ""
    let item = config.value.find(at => {
      return at.code == "city"
    })

    let list = provinceData.value.find(item => {
      return item.name == form.value.province
    })?.list || []

    item.list = list;

  }
}

const initPromise = async () => {
  let res = await Promise.all([GlobeStateDetailApi.getGlobeStateDetailPage({
    stateId: form.value.stateId
  })])


  let item = config.value.find(at => {
    return at.code == "province"
  })


  item.list = generateProvince(res[0]);

  console.log(item.list, "=========")

  provinceData.value = deepCopy(item.list);
}

const initData=async()=>{
  await initPromise();

  let item = config.value.find(at => {
    return at.code == "city"
  })

  let list = provinceData.value.find(item => {
    return item.name == form.value.province
  })?.list || []


  item.list = list;

}


/**
 * 生成省市区树
 * */
const generateProvince = (provinceData) => {
  console.log(provinceData)
  let cityList = [];
  provinceData?.list?.forEach(item => {
    let isIn = cityList.find(at => {
      return item.province == at.name
    })
    if (!isIn) {
      cityList.push({
        name: item.province,
        list: []
      })
    }
  })

  cityList.forEach(item => {
    let lis = provinceData?.list?.filter(it => {
      return it.province == item.name
    })

    item.list = (lis || []).map(item => {
      return {
        name: item.city,
        list: []
      }
    });

    // item.list.forEach(at => {
    //   let lisArea = provinceData.globeStateDetailList.filter(it => {
    //     return it.city == at.name
    //   })
    //
    //   at.list = (lisArea || []).map(z => {
    //     return {
    //       name: z.area,
    //       id: z.id
    //     }
    //   })
    // })
  })

  return cityList
}


const queryList = async () => {
  let res = await getGlobeState();
  let item = config.value.find(at => {
    return at.code == "stateId"
  })
  item.list = res
}

onMounted(() => {
  queryList();
})

defineExpose({
  confirm
})

watch(() => props.info, () => {
  form.value = props.info;
  if (props.info.id) {
      //TODO

    initData()
  }
}, {
  deep: true,
  immediate: true
})
</script>
<style lang="scss" scoped>

</style>
